import * as types from './type';

const state = () => {
    return {
        // 用户登录状态
        userToken: sessionStorage.getItem('userToken') || '',
        // 用户登录信息
        userInfo: JSON.parse(sessionStorage.getItem('userInfo')) || {},
        // 所有个人设置后的权限
        permission: JSON.parse(sessionStorage.getItem('permission')) || []
    }
};
const actions = {
  /**
   * session token
   */
  setToken ({commit}, data) {
    sessionStorage.setItem('userToken', data);
    commit(types.SET_LOGIN_STATUS, data);
  },
  /**
   * 用户登录
   */
  setUserInfo ({commit}, data) {
    sessionStorage.setItem('userInfo', JSON.stringify(data));
    commit(types.SET_USER_INFO, data);
  },
  // 所有个人设置后的权限
  setPermission ({commit}, data) {
    if (data === null) {
      data = [];
    };
    sessionStorage.setItem('permission', JSON.stringify(data));
    commit(types.SET_PERMISSION, data);
  },

  /**
   * 退出登录
   */
  setSignOut ({commit}) {
    commit(types.SET_LOGIN_STATUS, '');
    commit(types.SET_USER_INFO, {});
    commit(types.SET_PERMISSION, {});
    sessionStorage.removeItem('userToken');
    sessionStorage.removeItem('userInfo');
    sessionStorage.removeItem('permission');
  }
};

const getters = {
  userToken: state => state.userToken,
  userInfo: state => state.userInfo,
  permission: state => state.permission
};

const mutations = {
  [types.SET_USER_INFO] (state, res) {
    state.userInfo = res;
  },

  [types.SET_LOGIN_STATUS] (state, status) {
    state.userToken = status;
  },
  [types.SET_PERMISSION] (state, status) {
    state.permission = status;
  }
};

export default {
  state,
  actions,
  getters,
  mutations
};
